package com.jhgsys.internal.system.controller;


import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.*;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.DeptModel;
import com.jhgsys.internal.system.entity.Menu;
import com.jhgsys.internal.system.entity.MenuModel;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Slf4j
@RestController
@RequestMapping("dept")
public class DeptController extends BaseController {

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IUserService userService;


    @GetMapping
    @RequiresPermissions("dept:view")
    public FebsResponse getAllDeptForm(Dept dept) {
        return new FebsResponse().success().data(deptService.findDeptForm(dept));
    }

    @GetMapping("select/tree")
    @RequiresPermissions("dept:view")
    public List<DeptTree<Dept>> getDeptTree() throws FebsException {
        try {
            return this.deptService.findDepts();
        } catch (Exception e) {
            String message = "获取部门树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("tree")
    @RequiresPermissions("dept:view")
    public FebsResponse getDeptTree(Dept dept) throws FebsException {
        try {
            //不是总公司用户，只能看到自己公司（分公司）下的
            if(!hasHeadCompanyRole()){
                dept.setTenantId(getCurrentTenantId());
            }
            List<DeptTree<Dept>> depts = this.deptService.findDepts(dept);
            return new FebsResponse().success().data(depts);
        } catch (Exception e) {
            String message = "获取部门树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("treeNew")
    @RequiresPermissions("dept:view")
    public Object getDeptTreeNew(Dept dept) throws FebsException {
        try {
            if(StringUtils.isBlank(dept.getTenantId())){
                dept.setTenantId(getCurrentTenantId());
            }
            if(StringUtils.isNotBlank(dept.getDeptName())){
                List<DeptTreeNew<Dept>> depts = this.deptService.searchDepts(dept);
                DeptModel model = new DeptModel(depts,depts.size());
                return model;
            }
            DeptTreeNew<Dept> depts = this.deptService.findDeptsA(dept);
            DeptModel model = new DeptModel(depts.getChildren(),this.deptService.findDeptsCount(dept));
            return model;
        } catch (Exception e) {
            String message = "获取部门树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("treeSelect")
    @RequiresPermissions("dept:view")
    public Object getDeptTreeSelect(Dept dept) throws FebsException {
        try {
            dept.setTenantId(getCurrentTenantId());
            Object depts = this.deptService.findDeptsB(dept);
            return depts;
        } catch (Exception e) {
            String message = "获取部门树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 查询（所有）
     *
     * @author JHG
     * @date 2019-07-18 09:40:15
     */
    @GetMapping("alldept")
    @RequiresPermissions("dept:view")
    public FebsResponse getAlldepts(Dept dept) {
        return new FebsResponse().success().data(deptService.findDeptForm(dept));
    }

    /**
     * 查询（分页）
     * @author chenweihau
     * @date 2019-08-08 09:42:49
     */
    @GetMapping("list")
    @RequiresPermissions("dept:view")
    public FebsResponse basicDictList(QueryRequest request, Dept dept) {
        Map<String, Object> dataTable = getDataTable(this.deptService.findDepts(request, dept));
        return new FebsResponse().success().data(dataTable);
    }


    @Log("新增部门")
    @PostMapping
    @RequiresPermissions("dept:view")
    public FebsResponse addDept(@RequestBody Dept dept) throws FebsException {
        Dept deptParma = new Dept();
        deptParma.setTenantId(dept.getTenantId());
        deptParma.setDeptCode(dept.getDeptCode());
        List<Dept> deptList = this.deptService.findDeptForm(deptParma);
        if(null != deptList && deptList.size() > 0){
            throw new FebsException("部门编号已存在");
        }
        deptParma = new Dept();
        deptList = new ArrayList<>();
        deptParma.setTenantId(dept.getTenantId());
        deptParma.setBusinessCode(dept.getBusinessCode());
        deptList = this.deptService.findDeptForm(deptParma);
        if(null != deptList && deptList.size() > 0){
            throw new FebsException("业务编号已存在");
        }
        try {
            String userName= getCurrentUser().getUserName();
            dept.setCreatedBy(userName);
            this.deptService.createDept(dept);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增部门失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 删除部门
     *
     * @param deptIds
     * @return
     * @throws FebsException
     * @author qiny
     * @date 2019-07-23
     */
    @Log("删除部门")
    @GetMapping("delete/{deptIds}")
    @RequiresPermissions("dept:view")
    public FebsResponse deleteDepts(@NotBlank(message = "{required}") @PathVariable String deptIds) throws FebsException {
        try {
            String userName= getCurrentUser().getUserName();
            Dept dept = new Dept();
            dept.setDeletedBy(userName);
            dept.setDeletedTime(new Date());
            dept.setDeletedFlg(FebsConstant.INVALID);
            this.deptService.updateDeptDeletedFlg(deptIds, dept);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除部门失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改部门")
    @PostMapping("update")
    @RequiresPermissions("dept:view")
    public FebsResponse updateDept(@RequestBody Dept dept) throws FebsException {
        Dept deptParma = new Dept();
        List<Dept> collect = new ArrayList<>();
        deptParma.setTenantId(dept.getTenantId());
        deptParma.setDeptCode(dept.getDeptCode());
        List<Dept> deptList = this.deptService.findDeptForm(deptParma);
        if(null != deptList && deptList.size() > 0){
            collect = deptList.stream().filter(p -> !dept.getDeptId().equals(p.getDeptId())).collect(Collectors.toList());
        }
        if(null != collect && collect.size() > 0){
            throw new FebsException("部门编号已存在");
        }
        deptParma = new Dept();
        deptList = new ArrayList<>();
        collect = new ArrayList<>();
        deptParma.setTenantId(dept.getTenantId());
        deptParma.setBusinessCode(dept.getBusinessCode());
        deptList = this.deptService.findDeptForm(deptParma);
        if(null != deptList && deptList.size() > 0){
            collect = deptList.stream().filter(p -> !dept.getDeptId().equals(p.getDeptId())).collect(Collectors.toList());
        }
        if(null != collect && collect.size() > 0){
            throw new FebsException("业务编号已存在");
        }
        try {
            String userName= getCurrentUser().getUserName();
            dept.setUpdatedBy(userName);
            this.deptService.updateDept(dept);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改部门失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改菜单/按钮")
    @PostMapping("updateStatus")
    @RequiresPermissions("menu:update")
    public FebsResponse updateDeptStatus(@RequestBody Dept dept) throws FebsException {
        try {
            dept.setUpdatedBy(getCurrentUser().getUserName());
            this.deptService.updateDept(dept);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改菜单/按钮失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("excel")
    @RequiresPermissions("dept:view")
    public void export(Dept dept, QueryRequest request, HttpServletResponse response) throws FebsException {
        try {
//            List<Dept> depts = this.deptService.findDepts(dept, request);
//            ExcelKit.$Export(Dept.class, response).downXlsx(depts, false);

            this.deptService.exportDepts(request,dept, response);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 返回部门eletree
     * @param dept
     * @return
     * @throws FebsException
     */
    @GetMapping("eletree")
    public FebsResponse getDeptEleTree(Dept dept) throws FebsException {
        try {
            DeptTree<Dept> depts = this.deptService.findDeptEletree(dept);
            return new FebsResponse().success().data(depts.getChildren());
        } catch (Exception e) {
            String message = "获取部门树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

}

